document.addEventListener('DOMContentLoaded', () => {
    const alertInput = document.getElementById('alertInput');
    const analyzeBtn = document.getElementById('analyzeBtn');
    const analysisStepsContainer = document.getElementById('analysisSteps');

    const WEBSOCKET_API_URL = 'ws://localhost:8000/ws';
    let websocket = null;

    const stepDefinitions = {
        'InitialTriageNode': {
            title: '1. 初步分类与实体提取',
            icon: 'fas fa-search'
        },
        'IntelligenceGatheringNode': {
            title: '2. 情报收集',
            icon: 'fas fa-cloud-download-alt'
        },
        'ExpertJudgmentNode': {
            title: '3. 专家判断',
            icon: 'fas fa-brain'
        },
        'RefineInvestigationNode': {
            title: '4. 调查精炼',
            icon: 'fas fa-redo-alt'
        },
        'GenerateReportNode': {
            title: '5. 报告生成',
            icon: 'fas fa-file-alt'
        },
        'UnsupportedEventNode': {
            title: '事件类型不支持',
            icon: 'fas fa-exclamation-triangle',
            description: '系统无法识别或处理此事件类型，请手动分析。'
        }
    };

    // 威胁情报工具定义
    const threatIntelToolDefinitions = {
        'Threat_Intel_Parallel_Query': {
            title: '威胁情报并行查询',
            icon: 'fas fa-network-wired',
            description: '同时查询多个威胁情报源'
        },
        'OTX_Query': {
            title: 'AlienVault OTX',
            icon: 'fas fa-shield-alt',
            description: '开源威胁情报平台'
        },
        'VirusTotal_Query': {
            title: 'VirusTotal',
            icon: 'fas fa-virus',
            description: '多引擎恶意软件检测'
        },
        'APIVoid_Dispatcher': {
            title: 'APIVoid 调度器',
            icon: 'fas fa-route',
            description: 'APIVoid 威胁情报调度'
        },
        'APIVoid_IP_Query': {
            title: 'APIVoid IP 信誉',
            icon: 'fas fa-globe',
            description: 'IP地址信誉检查'
        },
        'APIVoid_Domain_Query': {
            title: 'APIVoid 域名信誉',
            icon: 'fas fa-link',
            description: '域名信誉检查'
        },
        'APIVoid_URL_Query': {
            title: 'APIVoid URL 信誉',
            icon: 'fas fa-external-link-alt',
            description: 'URL信誉检查'
        },
        // 添加缺失的威胁情报工具定义
        'analyze_user_agent': {
            title: '检查扫描工具的UserAgent',
            icon: 'fas fa-user-secret',
            description: '分析用户代理字符串'
        },
        'batch_detect_dga_domains': {
            title: '批量检测提取的域名是否为DGA',
            icon: 'fas fa-search',
            description: '检测域名生成算法'
        },
        'batch_query_threat_intelligence': {
            title: '批量查询DGA可疑域名的威胁情报',
            icon: 'fas fa-database',
            description: '批量威胁情报查询'
        },
        'query_threat_intelligence': {
            title: '查询威胁情报',
            icon: 'fas fa-shield-alt',
            description: '威胁情报查询'
        }
    };

    // 威胁情报工具状态元素映射
    let toolStatusElements = {};

    // 创建威胁情报工具状态卡片
    function createThreatIntelToolCard(toolName, toolInfo) {
        const cardId = `threat-intel-tool-${toolName}`;
        const cardHtml = `
            <div id="${cardId}" class="threat-intel-tool-card">
                <div class="tool-header">
                    <div class="tool-icon">
                        <i class="${toolInfo.icon}"></i>
                    </div>
                    <div class="tool-info">
                        <div class="tool-title">${toolInfo.title}</div>
                        <div class="tool-description">${toolInfo.description}</div>
                    </div>
                    <div class="tool-status">
                        <span class="status-indicator status-running">
                            <i class="fas fa-spinner fa-spin"></i> 查询中...
                        </span>
                    </div>
                </div>
                <div class="tool-result" style="display: none;">
                    <!-- 工具结果将在这里显示 -->
                </div>
            </div>
        `;
        return cardHtml;
    }

    // 更新威胁情报工具状态
    function updateThreatIntelToolStatus(toolName, status, data = null) {
        const cardElement = document.getElementById(`threat-intel-tool-${toolName}`);
        if (!cardElement) return;

        const statusIndicator = cardElement.querySelector('.status-indicator');
        const toolResult = cardElement.querySelector('.tool-result');

        switch (status) {
            case 'success':
                statusIndicator.className = 'status-indicator status-success';
                statusIndicator.innerHTML = '<i class="fas fa-check-circle"></i> 完成';

                if (data && data.result) {
                    toolResult.style.display = 'block';
                    toolResult.innerHTML = formatThreatIntelResult(data.result);

                    // 特殊处理威胁情报查询工具，显示最终情报收集结果
                    if (toolName === 'query_threat_intelligence') {
                        displayGatheredIntelligence(null, data.result);
                    }
                }
                break;
            case 'failed':
                statusIndicator.className = 'status-indicator status-error';
                statusIndicator.innerHTML = '<i class="fas fa-times-circle"></i> 失败';

                if (data && data.error) {
                    toolResult.style.display = 'block';
                    toolResult.innerHTML = `<div class="error-message">${escapeHtml(data.error)}</div>`;
                }
                break;
            case 'skipped':
                statusIndicator.className = 'status-indicator status-skipped';
                statusIndicator.innerHTML = '<i class="fas fa-forward"></i> 跳过';

                if (data && data.message) {
                    toolResult.style.display = 'block';
                    toolResult.innerHTML = `<div class="result-summary"><strong>原因:</strong> ${escapeHtml(data.message)}</div>`;
                }
                break;
        }
    }

    // 格式化威胁情报结果显示
    function formatThreatIntelResult(result) {
        if (!result || typeof result !== 'object') {
            return '<div class="result-summary">无结果数据</div>';
        }

        // 如果是标准化格式的威胁情报结果
        if (result.source && result.data) {
            const source = result.source;
            const data = result.data;
            const status = result.status;

            if (status === 'success' && data) {
                return `
                    <div class="result-summary">
                        <strong>来源:</strong> ${escapeHtml(source)}<br>
                        <strong>状态:</strong> <span class="status-success">成功</span><br>
                        <div class="result-details">
                            <details>
                                <summary>查看详细数据</summary>
                                <pre><code>${escapeHtml(JSON.stringify(data, null, 2))}</code></pre>
                            </details>
                        </div>
                    </div>
                `;
            } else {
                return `
                    <div class="result-summary">
                        <strong>来源:</strong> ${escapeHtml(source)}<br>
                        <strong>状态:</strong> <span class="status-error">失败</span><br>
                        <strong>错误:</strong> ${escapeHtml(result.error || '未知错误')}

                    </div>
                `;
            }
        }

        // 兜底显示原始JSON
        return `
            <div class="result-details">
                <details>
                    <summary>查看结果数据</summary>
                    <pre><code>${escapeHtml(JSON.stringify(result, null, 2))}</code></pre>
                </details>
            </div>
        `;
    }

    // 处理威胁情报工具消息
    function handleThreatIntelToolMessage(type, toolName, data) {
        // 检查是否是威胁情报工具
        if (!threatIntelToolDefinitions[toolName]) {
            // 如果不是已知的威胁情报工具，按原有逻辑处理
            return false;
        }

        switch (type) {
            case 'tool_start':
                handleThreatIntelToolStart(toolName, data);
                break;
            case 'tool_end':
                handleThreatIntelToolEnd(toolName, data);
                break;
            case 'tool_error':
                handleThreatIntelToolError(toolName, data);
                break;
            case 'tool_skipped':
                updateThreatIntelToolStatus(toolName, 'skipped', data);
                break;
        }
        return true;
    }

    // 处理威胁情报工具开始
    function handleThreatIntelToolStart(toolName, data) {
        // 确保在IntelligenceGatheringNode中显示威胁情报工具
        const intelligenceStep = document.getElementById('step-IntelligenceGatheringNode');
        if (!intelligenceStep) return;

        // 清理可能存在的多余工具执行信息
        const stepContent = intelligenceStep.querySelector('.step-content');
        if (stepContent) {
            // 移除所有威胁情报相关工具的执行信息元素
            const toolElements = stepContent.querySelectorAll('[data-key^="tool-"]');
            toolElements.forEach(element => {
                const key = element.dataset.key;
                if (key.includes('threat_intelligence') ||
                    key.includes('query') ||
                    key.includes('detect') ||
                    key.includes('analyze') ||
                    key.includes('batch_')) {
                    element.remove();
                }
            });
        }

        let threatIntelContainer = intelligenceStep.querySelector('.threat-intel-container');
        if (!threatIntelContainer) {
            // 创建威胁情报容器
            const stepContent = intelligenceStep.querySelector('.step-content');
            threatIntelContainer = document.createElement('div');
            threatIntelContainer.className = 'threat-intel-container';
            threatIntelContainer.innerHTML = `
                <div class="threat-intel-tools"></div>
            `;
            stepContent.appendChild(threatIntelContainer);
        }

        const toolsContainer = threatIntelContainer.querySelector('.threat-intel-tools');
        const toolInfo = threatIntelToolDefinitions[toolName];

        // 创建工具卡片
        const toolCard = document.createElement('div');
        toolCard.innerHTML = createThreatIntelToolCard(toolName, toolInfo);
        toolsContainer.appendChild(toolCard.firstElementChild);

        // 保存到映射中
        toolStatusElements[toolName] = document.getElementById(`threat-intel-tool-${toolName}`);
    }

    // 处理威胁情报工具完成
    function handleThreatIntelToolEnd(toolName, data) {
        updateThreatIntelToolStatus(toolName, 'success', data);
    }

    // 处理威胁情报工具错误
    function handleThreatIntelToolError(toolName, data) {
        updateThreatIntelToolStatus(toolName, 'failed', data);
    }

    function resetAnalysisUI() {
        // 清空威胁情报工具状态映射
        toolStatusElements = {};
        stepNameToToolNameMap = {}; // 新增：重置映射

        analysisStepsContainer.innerHTML = `
            <div class="step-item loading-placeholder">
                <div class="step-header">
                    <div class="step-icon"><i class="fas fa-spinner fa-spin"></i></div>
                    <div class="step-title">等待分析开始...</div>
                </div>
                <div class="step-content">
                    <p>请在左侧输入告警数据并点击“开始分析”按钮。</p>
                </div>
            </div>
        `;
    }

    function createOrUpdateStep(stepName, status, message) {
        let stepItem = document.getElementById(`step-${stepName}`);
        const stepDef = stepDefinitions[stepName];

        if (!stepItem && stepDef) {
            if (analysisStepsContainer.querySelector('.loading-placeholder')) {
                analysisStepsContainer.innerHTML = '';
            }
            stepItem = document.createElement('div');
            stepItem.id = `step-${stepName}`;
            stepItem.classList.add('step-item');
            
            stepItem.innerHTML = `
                    <div class="step-header">
                        <div class="step-icon"><i class="${stepDef.icon}"></i></div>
                       <div class="step-title">${stepDef.title}</div>
                        <span class="step-status status-${status}">${status.toUpperCase()}</span>
                    </div>
                    <div class="step-content" data-is-pristine="true">
                        ${(stepName === 'InitialTriageNode' ||
                           stepName === 'ExpertJudgmentNode' ||
                           stepName === 'RefineInvestigationNode' ||
                           stepName === 'GenerateReportNode') ? `
                            <div class="thinking-container">
                                <div class="thinking-header" onclick="toggleThinking(this)">
                                    <span class="thinking-arrow">▶</span>
                                    <span class="thinking-title">思考中<span class="thinking-dots">...</span></span>
                                    <span class="thinking-pulse"></span>
                                </div>
                                <div class="thinking-content" style="display: none;">
                                    <pre><code></code></pre>
                                </div>
                            </div>
                        ` : ''}
                        <div class="result-display"></div>
                    </div>
                `;
            
            // 为 GenerateReportNode 的结果容器设置特定ID
            if (stepName === 'GenerateReportNode') {
                stepItem.querySelector('.result-display').id = 'final-report-container';
            }

            // 默认展开 InitialTriageNode, ExpertJudgmentNode 和 GenerateReportNode 的思考容器
            if (stepName === 'InitialTriageNode' || stepName === 'ExpertJudgmentNode' || stepName === 'GenerateReportNode') {
                const thinkingContainer = stepItem.querySelector('.thinking-container');
                const thinkingContent = thinkingContainer.querySelector('.thinking-content');
                const thinkingArrow = thinkingContainer.querySelector('.thinking-arrow');
                if (thinkingContent && thinkingArrow) {
                    thinkingContent.style.display = 'block';
                    thinkingArrow.textContent = '▼';
                }
            }
            analysisStepsContainer.appendChild(stepItem);
            stepItem.querySelector('.step-header').addEventListener('click', () => {
                stepItem.classList.toggle('expanded');
            });
        }

        if (stepItem) {
            const statusSpan = stepItem.querySelector('.step-status');
            statusSpan.className = `step-status status-${status}`;
            statusSpan.textContent = status.toUpperCase();
            
            // 移除状态消息更新逻辑，保持界面简洁

            document.querySelectorAll('.step-item').forEach(item => item.classList.remove('active'));
            if (status === 'running') {
                stepItem.classList.add('active', 'expanded');
            }
        }
    }

    function appendOrUpdateContent(container, key, htmlContent, isCollapsible = false, title = key) {
        let element = container.querySelector(`[data-key="${key}"]`);
        if (!element) {
            element = document.createElement('div');
            element.dataset.key = key;
            element.classList.add('details-box');
            if (isCollapsible) {
                element.classList.add('collapsible');
                element.innerHTML = `<h4 class="collapsible-header">${escapeHtml(title)}</h4><div class="collapsible-content"><pre><code></code></pre></div>`;
                element.querySelector('.collapsible-header').addEventListener('click', (e) => {
                    e.currentTarget.parentElement.classList.toggle('expanded');
                });
            } 
            container.appendChild(element);
        }
        
        if (isCollapsible) {
            element.querySelector('pre code').innerHTML = htmlContent;
        } else {
            element.innerHTML = htmlContent;
        }
    }
    
    function appendStreamContent(container, key, chunk, title) {
        let element = container.querySelector(`[data-key="${key}"]`);
        if (!element) {
            element = document.createElement('div');
            element.dataset.key = key;
            element.classList.add('details-box');

            // 统一使用简洁的容器结构
            element.innerHTML = `<h4>${escapeHtml(title)}</h4><pre><code></code></pre>`;
            container.appendChild(element);
        }

        // 统一的内容追加逻辑
        const codeBlock = element.querySelector('pre code');
        if (codeBlock) {
            codeBlock.textContent += chunk;
        }
    }

    function handleBackendStatusUpdate(message) {
        const { type, step, data } = message;

        // 优先处理威胁情报工具消息
        if (type.startsWith('tool_')) {
            if (handleThreatIntelToolMessage(type, step, data)) {
                return; 
            }
        }

        const targetStep = step;
        if (!stepDefinitions[targetStep]) {
            console.log('未找到步骤定义:', targetStep);
            return;
        }

        // 确保步骤容器存在，必要时创建它。
        let stepItem = document.getElementById(`step-${targetStep}`);
        if (!stepItem) {
            createOrUpdateStep(targetStep, 'running', data ? data.message : '...');
            stepItem = document.getElementById(`step-${targetStep}`);
        }

        const stepContent = stepItem ? stepItem.querySelector('.step-content') : null;

        if (!stepContent) {
            console.log('未找到步骤内容容器:', `step-${targetStep}`);
            return;
        }

        switch (type) {
            case 'node_start':
                createOrUpdateStep(step, 'running');
                break;
            case 'node_end':
                createOrUpdateStep(step, 'completed');
                finishThinking(stepContent);

                // 特定节点的最终结果处理
                if (step === 'ExpertJudgmentNode' && (data.judgment_result || data.message)) {
                    addExpertJudgmentResult(stepContent, data);
                } else if (step === 'IntelligenceGatheringNode' && data.gathered_intelligence) {
                    displayGatheredIntelligence(stepContent, data.gathered_intelligence);
                } else if (step === 'RefineInvestigationNode' && data.directive) { // 处理调查精炼节点的最终指令
                    addInvestigationDirectiveDisplay(stepContent, data.directive);
                }
                break;
            case 'llm_reasoning_chunk':
            case 'llm_raw_chunk':
            case 'llm_chunk':
                // 确保 thinkingContainer 的 dataset.thinking 状态被设置
                const thinkingContainerForChunk = stepContent.querySelector('.thinking-container');
                if (thinkingContainerForChunk) {
                    thinkingContainerForChunk.dataset.thinking = 'true';
                }
                appendCollapsibleThinking(stepContent, data.chunk);
                break;
            case 'llm_parsed_result':
                finishThinking(stepContent);
                addParsedResultDisplay(stepContent, data.parsed_result);
                break;
            case 'entity_extracted':
                // 移除实体提取的显示，现在通过 llm_parsed_result 统一处理
                break;
            case 'final_report_complete':
                let finalReportContainer = document.getElementById('final-report-container');
                if (finalReportContainer) {
                    finalReportContainer.innerHTML = `<pre><code>${escapeHtml(data.report_content)}</code></pre>`;
                    const stepItem = finalReportContainer.closest('.step-item');
                    if(stepItem) {
                        const statusSpan = stepItem.querySelector('.step-status');
                        if(statusSpan) {
                            statusSpan.className = 'step-status status-completed';
                            statusSpan.textContent = 'COMPLETED';
                        }
                        // 确保思考容器状态更新
                        finishThinking(stepItem.querySelector('.step-content'));
                    }
                }
                break;
            case 'error':
                createOrUpdateStep(step, 'error', data.message || data.error);
                break;
            default:
                console.log('未知消息类型:', message);
        }
    }

    function connectWebSocket() {
        if (websocket && websocket.readyState === WebSocket.OPEN) return;
        websocket = new WebSocket(WEBSOCKET_API_URL);

        websocket.onopen = () => {
            console.log('WebSocket连接已建立');
            analyzeBtn.disabled = false;
            analyzeBtn.innerHTML = '<span class="icon"><i class="fas fa-play"></i></span> 开始分析';
        };

        websocket.onmessage = (event) => {
            const message = JSON.parse(event.data);
            handleBackendStatusUpdate(message);
        };

        websocket.onclose = () => {
            console.log('WebSocket连接已关闭');
            analyzeBtn.disabled = true;
            analyzeBtn.innerHTML = '<span class="icon"><i class="fas fa-times-circle"></i></span> 连接断开';
            setTimeout(connectWebSocket, 3000);
        };

        websocket.onerror = (error) => {
            console.error('WebSocket错误:', error);
            websocket.close();
        };
    }

    connectWebSocket();

    analyzeBtn.addEventListener('click', () => {
        const alertData = alertInput.value.trim();
        if (!alertData) {
            alert('请输入告警数据！');
            return;
        }

        if (websocket && websocket.readyState === WebSocket.OPEN) {
            resetAnalysisUI();
            analyzeBtn.disabled = true;
            analyzeBtn.innerHTML = '<span class="icon"><i class="fas fa-spinner fa-spin"></i></span> 分析中...';

            websocket.send(JSON.stringify({
                type: 'start_analysis',
                alert_data: alertData
            }));
        } else {
            alert('WebSocket连接未建立或已关闭，请稍后再试或刷新页面。');
            connectWebSocket();
        }
    });

    function appendCollapsibleThinking(container, chunk) {
        const thinkingContainer = container.querySelector('.thinking-container');
        if (!thinkingContainer) { // 如果 thinkingContainer 不存在，可能是因为节点类型不支持思考过程，直接返回
            console.warn('Thinking container not found for step content.');
            return;
        }

        // 当思考开始时，移除初始的状态消息
        const statusMessage = container.querySelector('p.status-message');
        if (statusMessage) {
            statusMessage.remove();
        }

        const codeBlock = thinkingContainer.querySelector('code');
        if (codeBlock) { 
            codeBlock.textContent += chunk;
        }

        // 自动滚动到最新内容
        const thinkingContent = thinkingContainer.querySelector('.thinking-content');
        if (thinkingContent && thinkingContent.style.display !== 'none') {
            // 使用 setTimeout 确保 DOM 更新后再滚动
            setTimeout(() => {
                thinkingContent.scrollTop = thinkingContent.scrollHeight;
            }, 0);
        }
    }

    // 完成思考时调用
    function finishThinking(container) {
        const thinkingContainer = container.querySelector('.thinking-container');
        if (thinkingContainer && thinkingContainer.dataset.thinking === 'true') {
            const titleElement = thinkingContainer.querySelector('.thinking-title');
            const pulseElement = thinkingContainer.querySelector('.thinking-pulse');
            const thinkingContent = thinkingContainer.querySelector('.thinking-content');
            const thinkingArrow = thinkingContainer.querySelector('.thinking-arrow');

            // 更新标题状态
            titleElement.innerHTML = '已深度思考';
            if (pulseElement) pulseElement.remove();
            thinkingContainer.dataset.thinking = 'false';

            // 自动折叠思考容器
            if (thinkingContent && thinkingArrow) {
                thinkingContent.style.display = 'none';
                thinkingArrow.textContent = '▶';
            }
        }
    }

    // 在思考容器后添加解析结果显示
    function addParsedResultDisplay(container, parsedResult) {
        if (!parsedResult) return;

        const resultDisplay = container.querySelector('.result-display');
        if (!resultDisplay) {
            console.error('Result display container not found for parsed result.');
            return;
        }

        // 创建紧凑的表格式结果展示HTML
        let resultHtml = `
            <h4>解析结果</h4>
            <table class="result-table">
        `;

        // 定义字段映射和样式类型
        const fieldMapping = {
            'event_type': { label: '事件类型', class: 'value-event-type' },
            'source_ip': { label: '源IP', class: 'value-ip' },
            'destination_ip': { label: '目标IP', class: 'value-ip' },
            'public_ips': { label: '公网IP', class: 'value-ip' },
            'private_ips': { label: '内网IP', class: 'value-ip' },
            'extracted_domains': { label: '域名', class: 'value-domain' },
            'domain': { label: '域名', class: 'value-domain' },
            'domains': { label: '域名', class: 'value-domain' },
            'URL': { label: 'URL', class: 'value-url' },
            'url': { label: 'URL', class: 'value-url' },
            'request_path': { label: '请求路径', class: 'value-url' },
            'user_agent': { label: 'User Agent', class: '' }
        };

        for (const [key, value] of Object.entries(parsedResult)) {
            const field = fieldMapping[key] || { label: key, class: '' };
            const valueClass = field.class ? ` class="${field.class}"` : '';

            resultHtml += `
                <tr>
                    <td>${field.label}</td>
                    <td${valueClass}>${escapeHtml(String(value))}</td>
                </tr>
            `;
        }

        resultHtml += '</table>';
        resultDisplay.innerHTML = resultHtml;

        // 在添加解析结果后，自动收缩思考容器
        const thinkingContainer = container.querySelector('.thinking-container');
        if (thinkingContainer) {
            const thinkingContent = thinkingContainer.querySelector('.thinking-content');
            const thinkingArrow = thinkingContainer.querySelector('.thinking-arrow');
            if (thinkingContent && thinkingArrow) {
                thinkingContent.style.display = 'none';
                thinkingArrow.textContent = '▶';
            }
        }
    }

    // 在思考容器后添加自然的分析结果
    function addNaturalAnalysisResult(container, data) {
        console.log('addNaturalAnalysisResult 接收到的数据:', data); // 调试输出

        // 检查是否已经添加过结果
        if (container.querySelector('.natural-analysis-result')) {
            console.log('已存在分析结果，跳过添加');
            return;
        }

        if (!data) {
            console.log('没有数据，跳过添加分析结果');
            return;
        }

        const judgment = data.judgment || '未知';
        const confidence = data.confidence || '无';
        const keyFactors = data.key_factors || '无';
        const evidenceAnalysis = data.evidence_analysis || {};

        let resultHtml = `
            <div class="natural-analysis-result">
                <p><strong>最终判断：</strong><span class="judgment-badge judgment-${judgment.toLowerCase().replace(' ', '-')}}">${judgment}</span></p>
        `;

        if (confidence !== '无') {
            resultHtml += `<p><strong>置信度：</strong>${confidence}</p>`;
        }

        if (keyFactors !== '无') {
            resultHtml += `<p><strong>关键决策因素：</strong>${escapeHtml(keyFactors)}</p>`;
        }

        if (evidenceAnalysis.supporting_threat && evidenceAnalysis.supporting_threat.length > 0) {
            resultHtml += `
                <p><strong>支持真实威胁的证据：</strong></p>
                <ul>
                    ${evidenceAnalysis.supporting_threat.map(item => `<li>${escapeHtml(item)}</li>`).join('')}
                </ul>
            `;
        }

        if (evidenceAnalysis.supporting_benign && evidenceAnalysis.supporting_benign.length > 0) {
            resultHtml += `
                <p><strong>支持误报的证据：</strong></p>
                <ul>
                    ${evidenceAnalysis.supporting_benign.map(item => `<li>${escapeHtml(item)}</li>`).join('')}
                </ul>
            `;
        }

        resultHtml += '</div>';

        // 在思考容器后面插入结果
        const thinkingContainer = container.querySelector('.thinking-container');
        if (thinkingContainer) {
            thinkingContainer.insertAdjacentHTML('afterend', resultHtml);
        }
    }

    // 添加专家判断结果显示
    function addExpertJudgmentResult(container, data) {
        console.log('addExpertJudgmentResult 接收到的数据:', data); // 调试输出

        const resultDisplay = container.querySelector('.result-display');
        if (!resultDisplay) {
            console.error('Result display container not found for expert judgment.');
            return;
        }

        let resultHtml = '';

        if (data.judgment_result) {
            resultHtml += `
                <h4><i class="fas fa-brain"></i> 专家判断结果</h4>
                <div class="judgment-content">
                    <p><strong>判断结论:</strong> ${escapeHtml(data.judgment_result)}</p>
                </div>
            `;
        } else if (data.message) {
            resultHtml += `
                <h4><i class="fas fa-brain"></i> 专家判断结果</h4>
                <div class="judgment-content">
                    <p>${escapeHtml(data.message)}</p>
                </div>
            `;
        }

        resultHtml += '';
        resultDisplay.innerHTML = resultHtml;

        // 在添加结果后，自动收缩思考容器
        const thinkingContainer = container.querySelector('.thinking-container');
        if (thinkingContainer) {
            const thinkingContent = thinkingContainer.querySelector('.thinking-content');
            const thinkingArrow = thinkingContainer.querySelector('.thinking-arrow');
            if (thinkingContent && thinkingArrow) {
                thinkingContent.style.display = 'none';
                thinkingArrow.textContent = '▶';
            }
        }
    }

    window.toggleThinking = function(header) {
        const content = header.nextElementSibling;
        const arrow = header.querySelector('.thinking-arrow');

        if (content.style.display === 'none') {
            content.style.display = 'block';
            arrow.textContent = '▼';
            // 展开时自动滚动到最新内容
            setTimeout(() => {
                content.scrollTop = content.scrollHeight;
            }, 0);
        } else {
            content.style.display = 'none';
            arrow.textContent = '▶';
        }
    }

    function escapeHtml(unsafe) {
        if (typeof unsafe !== 'string') {
            if (unsafe === null || unsafe === undefined) return '';
            try {
                unsafe = JSON.stringify(unsafe, null, 2);
            } catch (e) {
                unsafe = String(unsafe);
            }
        }
        return unsafe
             .replace(/&/g, "&amp;")
             .replace(/</g, "&lt;")
             .replace(/>/g, "&gt;")
             .replace(/"/g, "&quot;")
             .replace(/'/g, "&#039;");
     }

    // 新增：将 JSON 对象渲染为美化的 HTML
    function renderJsonToHtml(jsonObj, indent = 0) {
        let html = '<div class="json-viewer" style="margin-left: ' + (indent * 20) + 'px;">';
        for (const key in jsonObj) {
            if (jsonObj.hasOwnProperty(key)) {
                const value = jsonObj[key];
                const type = typeof value;

                html += '<div class="json-line">';
                html += '<span class="json-key">"' + escapeHtml(key) + '": </span>';

                if (type === 'object' && value !== null) {
                    if (Array.isArray(value)) {
                        html += '<span class="json-bracket">[</span>';
                        if (value.length > 0) {
                            html += '<span class="json-toggle" onclick="toggleJson(this)">...</span>';
                            html += '<div class="json-content" style="display: none;">';
                            for (let i = 0; i < value.length; i++) {
                                html += renderJsonToHtml({[i]: value[i]}, indent + 1); // Wrap array items in temp object for consistent rendering
                            }
                            html += '</div>';
                        }
                        html += '<span class="json-bracket">]</span>';
                    } else {
                        html += '<span class="json-bracket">{</span>';
                        if (Object.keys(value).length > 0) {
                            html += '<span class="json-toggle" onclick="toggleJson(this)">...</span>';
                            html += '<div class="json-content" style="display: none;">';
                            html += renderJsonToHtml(value, indent + 1);
                            html += '</div>';
                        }
                        html += '<span class="json-bracket">}</span>';
                    }
                } else {
                    let valueClass = 'json-value ';
                    if (type === 'string') {
                        valueClass += 'json-string';
                        html += '<span class="' + valueClass + '">"' + escapeHtml(value) + '"></span>';
                    } else if (type === 'number') {
                        valueClass += 'json-number';
                        html += '<span class="' + valueClass + '">' + escapeHtml(value) + '</span>';
                    } else if (type === 'boolean') {
                        valueClass += 'json-boolean';
                        html += '<span class="' + valueClass + '">' + escapeHtml(value) + '</span>';
                    } else if (value === null) {
                        valueClass += 'json-null';
                        html += '<span class="' + valueClass + '">null</span>';
                    }
                }
                html += '</div>';
            }
        }
        html += '</div>';
        return html;
    }

    // 新增：JSON 折叠/展开功能
    window.toggleJson = function(element) {
        const content = element.nextElementSibling;
        if (content.style.display === 'none') {
            content.style.display = 'block';
            element.textContent = '-';
        } else {
            content.style.display = 'none';
            element.textContent = '...';
        }
    };

    // 新增：显示所有收集到的情报
    function displayGatheredIntelligence(container, gatheredIntelligenceData) {
        // 找到IntelligenceGatheringNode的step-content
        const intelligenceStep = document.getElementById('step-IntelligenceGatheringNode');
        if (!intelligenceStep) return; // 如果步骤项不存在，则退出

        let threatIntelContainer = intelligenceStep.querySelector('.threat-intel-container');
        
        // 如果容器不存在，则创建它（理论上在tool_start时应该已经创建）
        if (!threatIntelContainer) {
            const stepContent = intelligenceStep.querySelector('.step-content');
            threatIntelContainer = document.createElement('div');
            threatIntelContainer.className = 'threat-intel-container';
            threatIntelContainer.innerHTML = `
                <div class="threat-intel-header">
                    <h4><i class="fas fa-network-wired"></i> 最终情报收集结果</h4>
                </div>
                <div class="threat-intel-tools"></div>
            `;
            stepContent.appendChild(threatIntelContainer);
        } else {
            // 更新标题为最终结果
            const header = threatIntelContainer.querySelector('.threat-intel-header h4');
            if (header) {
                header.innerHTML = '<i class="fas fa-network-wired"></i> 最终情报收集结果';
            } else { // 如果没有header，则添加一个
                const headerDiv = document.createElement('div');
                headerDiv.className = 'threat-intel-header';
                headerDiv.innerHTML = '<h4><i class="fas fa-network-wired"></i> 最终情报收集结果</h4>';
                threatIntelContainer.prepend(headerDiv); // 添加到最前面
            }
        }

        const toolsContainer = threatIntelContainer.querySelector('.threat-intel-tools');
        if (!toolsContainer) return; // 应该不会发生

        // 清空之前实时显示的工具卡片
        toolsContainer.innerHTML = '';

        for (const stepName in gatheredIntelligenceData) {
            if (gatheredIntelligenceData.hasOwnProperty(stepName)) {
                const toolResult = gatheredIntelligenceData[stepName];
                const toolName = stepNameToToolNameMap[stepName] || stepName; // Fallback to stepName if toolName not mapped
                const toolInfo = threatIntelToolDefinitions[toolName] || { title: stepName, icon: 'fas fa-question-circle', description: '' };

                let status = 'success';
                let statusText = '完成';
                let statusIcon = 'fas fa-check-circle';
                let resultSummary = '';
                let resultDetailsHtml = '';

                if (toolResult && toolResult.status === 'skipped') {
                    status = 'skipped';
                    statusText = '跳过';
                    statusIcon = 'fas fa-forward';
                    resultSummary = `<strong>状态:</strong> 跳过 - ${escapeHtml(toolResult.reason || toolResult.message || '无原因')}`;
                } else if (toolResult && toolResult.error) {
                    status = 'error';
                    statusText = '失败';
                    statusIcon = 'fas fa-times-circle';
                    resultSummary = `<strong>状态:</strong> 失败 - ${escapeHtml(toolResult.error)}`;
                    resultDetailsHtml = `<div class="error-message">${escapeHtml(toolResult.error)}</div>`;
                } else if (Array.isArray(toolResult)) {
                    // Handle batch results (e.g., DGA detection)
                    status = 'success'; // Assume success if array is present
                    statusText = '完成';
                    statusIcon = 'fas fa-check-circle';
                    resultSummary = `<strong>状态:</strong> 成功 - 共 ${toolResult.length} 条结果`;
                    resultDetailsHtml = `
                        <div class="result-details">
                            <details>
                                <summary>查看详细数据</summary>
                                <pre><code>${escapeHtml(JSON.stringify(toolResult, null, 2))}</code></pre>
                            </details>
                        </div>
                    `;
                } else {
                    // Handle single results
                    status = 'success';
                    statusText = '完成';
                    statusIcon = 'fas fa-check-circle';
                    resultSummary = `<strong>状态:</strong> 成功`;
                    resultDetailsHtml = formatThreatIntelResult(toolResult);
                }

                toolsContainer.innerHTML += `
                    <div class="threat-intel-tool-card">
                        <div class="tool-header">
                            <div class="tool-icon">
                                <i class="${toolInfo.icon}"></i>
                            </div>
                            <div class="tool-info">
                                <div class="tool-title">${toolInfo.title}</div>
                                <div class="tool-description">${toolInfo.description}</div>
                            </div>
                            <div class="tool-status">
                                <span class="status-indicator status-${status}">
                                    <i class="${statusIcon}"></i> ${statusText}
                                </span>
                            </div>
                        </div>
                        <div class="tool-result">
                            ${resultSummary}
                            ${resultDetailsHtml}
                        </div>
                    </div>
                `;
            }
        }
    }

});

    // 新增：显示调查精炼指令
    function addInvestigationDirectiveDisplay(container, directive) {
        const resultDisplay = container.querySelector('.result-display');
        if (!resultDisplay) {
            console.error('Result display container not found for investigation directive.');
            return;
        }

        let resultHtml = `
            <h4><i class="fas fa-lightbulb"></i> 调查精炼指令</h4>
            <div class="directive-content">
                <p>${escapeHtml(directive)}</p>
            </div>
        `;
        resultDisplay.innerHTML = resultHtml;

        // 自动收缩思考容器
        const thinkingContainer = container.querySelector('.thinking-container');
        if (thinkingContainer) {
            const thinkingContent = thinkingContainer.querySelector('.thinking-content');
            const thinkingArrow = thinkingContainer.querySelector('.thinking-arrow');
            if (thinkingContent && thinkingArrow) {
                thinkingContent.style.display = 'none';
                thinkingArrow.textContent = '▶';
            }
        }
    }